package com.wind;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class WindServlet extends HttpServlet {

	public void init (ServletConfig config) throws ServletException {
		super.init(config);
		registerContraints();
	}

	protected void registerContraints() {		
		{
			WindType type = WindDatastore.addType("type", "Type", WindDatastoreServiceTypes.getInstance());
			type.addAttribute("code", "Code", true, true);
			type.addAttribute("name", "Name", true, false);
		}
		{
			WindType type = WindDatastore.addType("horizontalTab", "Horizontal Tab", WindDatastoreServiceAppEngine.getInstance());
			type.addAttribute("code", "Code", true, true);
			type.addAttribute("title", "Title", true, false);
			type.addAttribute("order", "order", true, true);
			type.addAttribute("url", "url", true, false);
		}
		
		{		
			WindType type = WindDatastore.addType("verticalMenuItem", "Vertical Menu Item", WindDatastoreServiceAppEngine.getInstance());
			type.addAttribute("code", "Code", true, true);
			type.addAttribute("title", "Title", true, false);
			type.addAttribute("order", "order", true, true);
			type.addAttribute("url", "url", true, false);
		}
		{		
			WindType type = WindDatastore.addType("dataTable", "Data Table", WindDatastoreServiceAppEngine.getInstance());
			type.addAttribute("code", "Code", true, true);
			type.addAttribute("title", "Title", true, false);
			type.addAttribute("dataType", "dataType", true, false);
		}
		{		
			WindType type = WindDatastore.addType("dataTableColumn", "Data Table Column", WindDatastoreServiceAppEngine.getInstance());
			type.addAttribute("code", "Code", true, true);
			type.addAttribute("title", "Title", true, false);
			type.addAttribute("dataTableCode", "dataTableCode", true, false);
		}
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		JSON jsonResponse = null;
		try {
			JSON jsonRequest = JSON.parse(req.getParameter("json"));
			String operation = jsonRequest.getString("operation");
			if(operation!=null) {
				if(operation.startsWith("datastore.")) {
					jsonResponse = WindDatastore.execute(jsonRequest);
				}
				if(operation.startsWith("registerContraints")) {
					registerContraints();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonResponse = new JSON();
			JSON jsonErrors = jsonResponse.addArray("errors");			
			JSON jsonError = jsonErrors.addArrayElement();
			jsonError.addAttribute("text", e.toString());
		}

		if(jsonResponse!=null) {
			String strResponse = jsonResponse.toString(); 
			resp.setContentType("text/plain");
			resp.getWriter().println(strResponse);
		}
	}
}
